package com.starinside.wp.service.impl;

import com.starinside.wp.domain.comment.Comment;
import com.starinside.wp.domain.comment.ExtCommentsSupport;
import com.starinside.wp.foundation.vo.WxParent;
import com.starinside.wp.repository.*;
import com.starinside.wp.service.CommentsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    CommentRepository commentRepository;

    @Autowired
    ExtCommentsRepository extCommentRepository;

    @Autowired
    WxParentRepository wxParentRepository;

    @Override
    public ExtCommentsSupport commentHostForResId(String resId){
        return extCommentRepository.findByResTypeAndResId(1, resId);
    }

    @Override
    public ExtCommentsSupport commentHostForResIdAndResType(String resId, int resType){
        return extCommentRepository.findByResTypeAndResId(resType, resId);
    }

    @Override
    public Comment addCommentForResIdAndResType(String uid, String cid, String resId, int resType,  String content,  String refCommentId){
        ExtCommentsSupport exo = extCommentRepository.findByResTypeAndResId(resType, resId);

        if(exo == null){
            exo = new ExtCommentsSupport();

            exo.setCommentCount(0);
            exo.setResId(resId);
            exo.setResType(resType);

            extCommentRepository.save(exo);
        }

        WxParent parent = wxParentRepository.findParentBy(cid, uid);

        Comment comment = new Comment();
        comment.setContent(content);

        if(!StringUtils.isEmpty(refCommentId)) {
            //处理回复
            Comment replyTarget = commentRepository.findCommentById(refCommentId);

            comment.setRefUserId(replyTarget.getUserId());
            comment.setRefUserType(replyTarget.getUserType());
            comment.setRefChildrenId(replyTarget.getChildrenId());
            comment.setRefUserName(replyTarget.getUserName());
        }

        comment.setUserType(1);
        comment.setUserId(uid);
        comment.setChildrenId(cid);
        comment.setUserName(parent.getParentName());
        comment.setExtObj(exo);

        commentRepository.save(comment);

        exo.setLastCommentId(comment.getId());
        exo.setLastCommentShortContent(content);
        exo.setLastPost(new Date());
        exo.setLastPostName(comment.getUserName());
        exo.setLastPostUserId(comment.getUserId());
        exo.setLastPostUserType(comment.getUserType());

        exo.setCommentCount(exo.getCommentCount() + 1);

        extCommentRepository.save(exo);

        return comment;
    }
}
